package com.jason.ladder.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.orm.jpa.JpaSystemException;
import org.springframework.security.providers.encoding.PasswordEncoder;
import org.springframework.security.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.jason.ladder.dao.UserDao;
import com.jason.ladder.model.User;
import com.jason.ladder.service.UserExistsException;
import com.jason.ladder.service.UserManager;


/**
 * Implementation of UserManager interface.
 *
 * @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a>
 */
@Service("userManager")

public class UserManagerImpl  implements UserManager {
    private PasswordEncoder passwordEncoder;
    private UserDao userDao;

    @Autowired
    public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }

    @Autowired
    public void setUserDao(UserDao userDao) {
     
        this.userDao = userDao;
    }

   

	public List<User> getUsersByRank() throws UsernameNotFoundException {
		return userDao.getUsersByRank();
	}

	public Integer getNextRank() {
		return userDao.getNextRank();
	}

	@Override
	public User getUser(String userId) {
		return userDao.getUser(userId);
	}

	@Override
	public User save(User user) throws UserExistsException{
		 // Get and prepare password management-related artifacts
        boolean passwordChanged = false;
        if (passwordEncoder != null) {
            // Check whether we have to encrypt (or re-encrypt) the password
            if (user.getVersion() == null) {
                // New user, always encrypt
                passwordChanged = true;
                user.setCurrentPlace(this.getNextRank());
            } else {
                // Existing user, check password in DB
            	
                String currentPassword = userDao.getUser(user.getId().intValue()).getPassword();
                if (currentPassword == null) {
                    passwordChanged = true;
                } else {
                    if (!currentPassword.equals(user.getPassword())) {
                        passwordChanged = true;
                    }
                }
            }

            // If password was changed (or new user), encrypt it
            if (passwordChanged) {
                user.setPassword(passwordEncoder.encodePassword(user.getPassword(), null));
            }
        } else {
            //log.warn("PasswordEncoder not set, skipping password encryption...");
        }
        try {
            return userDao.save(user);
        } catch (DataIntegrityViolationException e) {
            //e.printStackTrace();
            //log.warn(e.getMessage());
            throw new UserExistsException("User '" + user.getName() + "' already exists!");
        } catch (JpaSystemException e) { // needed for JPA
            //e.printStackTrace();
            //log.warn(e.getMessage());
            throw new UserExistsException("User '" + user.getName() + "' already exists!");
        }
	}

	@Override
	public void remove(User user) {
		userDao.remove(user);
		
	}
}
